#include "myfile.h"
FILE_ *fopen_(const char *path_name, const char *mode)
{
    int flag = 0; // 文件打开方式
    if (strcmp("w", mode) == 0)
    {
        flag = flag | O_CREAT | O_WRONLY | O_TRUNC;
    }
    else if (strcmp("r", mode) == 0)
    {
        flag = flag | O_RDONLY;
    }
    else if (strcmp("a", mode) == 0)
    {
        flag = flag | O_APPEND | O_WRONLY | O_CREAT;
    }
    int id = 0; // 文件描述符
    if (flag & O_RDONLY)
        id = open(path_name, flag);
    else
        id = open(path_name, flag, 0666);
    if (id == -1)
    {
        // 打开失败收集打印错误信息
        const char *err = strerror(errno);
        write(2, err, strlen(err));
        return NULL;
    }
    // FILE结构体初始化
    FILE_ *fp = (FILE_ *)malloc(sizeof(FILE_));
    fp->flags = SYNC_LINE; // 默认设置为行刷新
    fp->fileno = id;
    fp->size = 0;
    fp->cap = SIZE;
    memset(fp->buffer, 0, SIZE);
    return fp;
}
void fwrite_(const void *ptr, int num, FILE_ *fp)
{
    memcpy(fp->buffer + fp->size, ptr, num);
    fp->size += num;
    if (fp->flags & SYNC_NOW)
    {
        write(fp->fileno, fp->buffer, fp->size);
        fp->size = 0;
    }
    else if (fp->flags & SYNC_LINE)
    {
        if (fp->buffer[fp->size - 1] == '\n')
        {
            write(fp->fileno, fp->buffer, fp->size);
            fp->size = 0;
        }
    }
    else if (fp->flags & SYNC_FULL)
    {
        if (fp->size == fp->cap)
        {
            write(fp->fileno, fp->buffer, fp->size);
            fp->size = 0;
        }
    }
}

void fflush_(FILE_ *fp)
{
    if (fp->size > 0)
    {
        write(fp->fileno, fp->buffer, fp->size);
        fsync(fp->fileno); // 将数据强制刷新至磁盘
    }
}
void fclose_(FILE_ *fp)
{
    fflush_(fp);
    close(fp->fileno);
}